package com.bbcare.department.plat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.OSSClientUtil;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.BrowsDetail;
import com.bbcare.department.plat.entity.EducationContent;
import com.bbcare.department.plat.entity.EducationContentInfo;
import com.bbcare.department.plat.entity.EducationTemplate;
import com.bbcare.department.plat.service.IEducationManagerService;
import com.bbcare.department.plat.store.ibatis.IEducationDao;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;

@Service
public class EducationManagerService implements IEducationManagerService {

	Logger logger = Logger.getLogger(EducationManagerService.class);

	@Autowired
	private IEducationDao educationDao;

	@Autowired
    private IPatientDAO patientDao;

	/**
	 * 查询宣教详情
	 * @param arg
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional
    public EducationContentInfo getEducationContentById(Map<String,Object> param) throws Exception {
        logger.info("in getEducationContentById----arg==" + param);
        String id = (String)param.get("id");
        EducationContentInfo info =educationDao.selectContentById(param);
        if(null == info){
        	throw  new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_EDUCATION_NOT_EXIST,"宣教内容不存在");
        }
        //更新浏览量  插入浏览记录  app端浏览时时候插入
        if(null != param.get("resource")){
        	Map<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("id",id);
            educationDao.updateBrowse(paramMap);

            BrowsDetail browDetail = new BrowsDetail();
            browDetail.setCreateTime(DateUtil.getSysDateA());
            browDetail.setEducationId(id);
            browDetail.setType(0); //科室宣教
            browDetail.setId(SeqUtil.getSeqNo());
        }

//      DepartmentBasic departmentBasic = new DepartmentBasic();
//      org.apache.commons.beanutils.BeanUtils.populate(departmentBasic, map);
        logger.info(JSON.toJSON(info));
        return info;
    }

    /**
     * 宣教分页查询
     */
    @Override
	public List<EducationContentInfo> getContentlistByCondition(Map<String,Object> paramMap)
			throws Exception {
		logger.info("in selectContentlistByCondition");
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;

		Object object = paramMap.get("title");
		Object title = (object!=null &&!StringUtils.isEmpty(object)) ? "%"+object.toString()+"%" : object ;

//		paramMap.put("status",1);
		paramMap.put("title",title);
		paramMap.put("page", page);
		paramMap.put("rows", rows);

		List<EducationContentInfo> eEducationContentInfo=  educationDao.selectContentsByCondition(paramMap);
        logger.info("out selectContentlistByCondition");
		return eEducationContentInfo;
	}


    /**
	 * 查询宣教详情
	 * @param arg
	 * @return
	 * @throws Exception
	 */
    public EducationTemplate getTemplateById(Map<String,Object> map) throws Exception {
        logger.info("in getTemplateById----arg==");
        EducationTemplate  info = educationDao.selectTemplateById(map);
//        DepartmentBasic departmentBasic = new DepartmentBasic();
//        org.apache.commons.beanutils.BeanUtils.populate(departmentBasic, map);
        logger.info(JSON.toJSON(info));
        return info;
    }


    /**
     * 宣教模板分页查询
     */
    @Override
	public List<EducationTemplate> getTemplatelistByCondition(Map<String,Object> paramMap)
			throws Exception {
		logger.info("in getTemplatelistByCondition");
		Integer page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : null;
		Integer rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : null;


		Object object = paramMap.get("templateName");
		Object templateName = (object!=null &&!StringUtils.isEmpty(object)) ? "%"+object.toString()+"%" : object ;

		paramMap.put("templateName", templateName);
		if(page !=null && rows !=null){
			paramMap.put("page", rows*(page-1));
			paramMap.put("rows", rows);
		}
		paramMap.put("status","1"); //生效
		List<EducationTemplate> educationTemplate=  educationDao.selectTemplatesByCondition(paramMap);
        logger.info("out getTemplatelistByCondition");
		return educationTemplate;
	}

    /**
     * 更新浏览量
     */
    @Transactional
    public int browseModify(Map<String, Object> paramMap) throws Exception{
    	logger.info("in browseModify----arg==" );
    	int i = educationDao.updateBrowse(paramMap);
    	logger.info("out browseModify----arg==" );
        return i;
    }

    /**
     * 宣教暂停
     */
    @Transactional
    @Override
    public int stopEducation(EducationContent edu) throws Exception{
    	logger.info("in stopEducation----arg==" );
    	int i = educationDao.stopEducation(edu);
    	logger.info("out stopEducation----arg==" );
        return i;
    }


	@Override
	public int deleteyContentsByIds(List<String> list) throws Exception {
		logger.info("in deleteyContentsByIds");
        int i =  educationDao.deleteyIds(list);
        logger.info("out deleteyContentsByIds");
        return i;
	}


	@Override
	@Transactional
	public String educationModitfy(Map<String,Object> map) throws Exception {
		logger.info("in educationModitfyModify----arg==" );

		EducationContent educationContent =  new EducationContent();
		JSONObject param = (JSONObject)map;
		//查看模板是否存在
		Map<String,Object> templateMap = new HashMap<String,Object>();
		templateMap.put("status","1");
		templateMap.put("id",param.get("templateId"));
		EducationTemplate  info = educationDao.selectTemplateById(templateMap);
		if(null == info ){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_EDUCATION_TEMPLATE_NOT_EXIST,"宣教模板不存在");
		}

		//置顶功能
		if(null!= map.get("isTop") && (Constants.EDUCATION_TOP_STATUS.equals(map.get("isTop"))||
					Constants.EDUCATION_NOT_TOP_STATUS.equals(map.get("isTop")))){
			educationContent.setIsTop((String)map.get("isTop"));
		}

		educationContent.setCreateAuthor(param.getString("createAuthor"));//
		educationContent.setTemplateId(param.getString("templateId"));
		educationContent.setTemplateValue(param.getString("templateValue"));
		educationContent.setTitle(param.getString("templateName"));
		educationContent.setDeptId(param.getString("deptId"));
		educationContent.setId(param.getString("id"));
		educationContent.setContent(param.getString("content"));
		educationContent.setPriority(param.getString("priority"));
		educationContent.setType(param.getString("type"));
		educationContent.setBannelUrl(param.getString("bannelUrl"));
		educationContent.setTenentId(param.getString("tenantId"));
		if(null != param.getString("pushRule")){
			educationContent.setPushRule(param.getString("pushRule"));
		}
//		educationContent.setPushRule("");

		String qrCodeUrl = PropertiesUtils.getProperty("educationPreview");

    	if(StringUtils.isEmpty(educationContent.getId())){
    		educationContent.setId(SeqUtil.getSeqNo());
    		educationContent.setCreateTime(DateUtil.getSysDateA());
    		educationContent.setBrowseCount(0);
    		educationContent.setStatus("1");//正常
    		//设置地址二维码  固定url+contentId
    		String qrcode = "";
    		if(!StringUtils.isEmpty(qrCodeUrl)){
    			qrCodeUrl =  qrCodeUrl+"?contentId="+educationContent.getId();
    			qrcode = OSSClientUtil.uploadQrCode(qrCodeUrl,PropertiesUtils.getProperty("educationQrcode"),"png");
    			educationContent.setQrcode(qrcode);
    		}

    		//规则内容

    		//增加模板表 引用量
    		Map<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("id",educationContent.getTemplateId());
            educationDao.updateEducationTemplate(paramMap);

    		educationDao.save(educationContent);
    	}else{
    		educationContent.getId();
    		educationContent.setUpdateTime(DateUtil.getSysDateA());

    		//规则内容
    		educationDao.update(educationContent);
    	}
		return educationContent.getId();
	}

    public String browseSave(BrowsDetail browsDetail) throws Exception{
		//
    	return null;
    	}

	@Override
	public int getContentsCountByDeptId(Map<String,Object> map) throws Exception {
		// TODO Auto-generated method stub
		int i =educationDao.countByDepId(map);
		return i;
	}

	@Override
	public int getTemplateCount(Map<String,Object> map) throws Exception {
		int i = educationDao.templateCount(map);// TODO Auto-generated method stub
		return i;
	}

	@Override
	public List<Map<String,Object>> browseStatistics(Map<String, Object> paramMap)
			throws Exception {
		String flag = (String)paramMap.get("flag");

		List<Map<String,Object>> rsplist =new ArrayList<Map<String,Object>>();

		List<Map<String,Object>> list =new ArrayList<Map<String,Object>>();
		if("1".equals(flag)){//按月
			//最近6月 按年月
			list = educationDao.countBrowseByMonth(paramMap);
			String [] months = DateUtil.getLast6Months();

			Map<String,Object> map = new HashMap<String,Object>();
			for(int j=0;j<list.size();j++){
				map.put(list.get(j).get("date").toString(),list.get(j).get("count"));
			}
			for(int i = 0;i<months.length ;i++){
				Map<String,Object> mapTemp = new HashMap<String,Object>();

				if(!map.containsKey(months[i])){
					mapTemp.put("count",0);
					mapTemp.put("date",months[i]);
					rsplist.add(mapTemp);
				}else{
					mapTemp.put("count",map.get(months[i]));
					mapTemp.put("date",months[i]);
					rsplist.add(mapTemp);
				}
			}
			return rsplist;
		}else{
			//最近7天  按年月日
			list = educationDao.countBrowseByDay(paramMap);

			String [] days = DateUtil.getLast7days();

			Map<String,Object> map = new HashMap<String,Object>();
			for(int j=0;j<list.size();j++){
				map.put(list.get(j).get("date").toString(),list.get(j).get("count"));
			}
			for(int i = 0;i<days.length ;i++){
				Map<String,Object> mapTemp = new HashMap<String,Object>();

				if(!map.containsKey(days[i])){
					mapTemp.put("count",0);
					mapTemp.put("date",days[i]);
					rsplist.add(mapTemp);
				}else{
					mapTemp.put("count",map.get(days[i]));
					mapTemp.put("date",days[i]);
					rsplist.add(mapTemp);
				}
			}
			return rsplist;
		}
	}

	@Override
	public List<Map<String, Object>> getContentlistforApp(
			Map<String, Object> paramMap) throws Exception {
		logger.info("in getContentlistforApp");
//		paramMap.put("userId", paramMap.get("paramMap"));
		Patient pt = patientDao.selectById(paramMap); //TODO  需修改成按 按队列+userId

		paramMap.put("status","1");
		//将科室宣教全部查出  再按逻辑处理
		List<Map<String, Object>> educationList =  educationDao.selectContentsForApp(paramMap);

		int age = 0;
		int correctAge = 0;

		int count = 6; //推送条数 最多6条
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		if(null != pt){
			if(!StringUtils.isEmpty(pt.getBirthday())){
				age = ToolUtils.getBirthAgeDay(pt.getBirthday());
				if(pt.getPregnancyDay()>0){
					Date date = new Date(ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay()));
					correctAge = ToolUtils.getBirthAgeDay(DateUtil.getDate_8(date));
				}else{
					correctAge = age; //没有填孕周   纠正年龄==出生年龄
				}
			}

			//计算建档时间和当前时间 天数
			Date createTime = DateUtil.getDateA(pt.getCreateTime());
			long day = ((new Date().getTime() - createTime.getTime())/(1000*60*60*24));

			List<Map<String, Object>> globalList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> ageList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> correctAgeList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> gisterTimeList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> randomList = new ArrayList<Map<String, Object>>();

			String pushRules="";
			if(!CollectionUtils.isEmpty(educationList)){
				for(Map<String, Object> tempMap:educationList){
					if(Constants.EDUCATION_PUSH_TYPE_GLOBAL.equals(tempMap.get("type"))){
						globalList.add(tempMap);
					}else if(Constants.EDUCATION_PUSH_TYPE_CORRECT_AGE.equals(tempMap.get("type"))){
						//规则格式为  start-end 中间用 "-" 区分
						pushRules = (null == tempMap.get("pushRule")) ? null : String.valueOf(tempMap.get("pushRule"));
						if(null != pushRules){
							if(pushRules.split("-",2).length == 2){
								String start = pushRules.split("-",2)[0];
								String end = pushRules.split("-",2)[1];
								if(StringUtils.isEmpty(start) && StringUtils.isEmpty(end)){
									correctAgeList.add(tempMap); //无具体规则
								}else{
									if(!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)){//开始和结束都传入
										if(ToolUtils.isNumeric(start) && ToolUtils.isNumeric(end)){
											if(correctAge>=Integer.parseInt(start) && correctAge<=Integer.parseInt(end)){
												correctAgeList.add(tempMap);
											}
										}else{
											correctAgeList.add(tempMap); //无具体规则
										}

									}else if(!StringUtils.isEmpty(start)){ //只传入开始时间
										if(ToolUtils.isNumeric(start)){
											if(correctAge>=Integer.parseInt(start)){
												correctAgeList.add(tempMap);
											}
										}else{
											correctAgeList.add(tempMap); //无具体规则
										}

									}else if(!StringUtils.isEmpty(end)){//只传入结束时间
										if(ToolUtils.isNumeric(end)){
											if(correctAge<=Integer.parseInt(end)){
												correctAgeList.add(tempMap);
											}
										}else{
											correctAgeList.add(tempMap); //无具体规则
										}
									}
								}
							}else{
								correctAgeList.add(tempMap); //无具体规则
							}
						}else{ //没有规则限制 默认可以推送
							correctAgeList.add(tempMap);
						}

					}else if(Constants.EDUCATION_PUSH_TYPE_AGE.equals(tempMap.get("type"))){
						pushRules = (null == tempMap.get("pushRule")) ? null : String.valueOf(tempMap.get("pushRule"));
						if(null != pushRules){
							if(pushRules.split("-",2).length == 2){
								String start = pushRules.split("-",2)[0];
								String end = pushRules.split("-",2)[1];
								if(StringUtils.isEmpty(start) && StringUtils.isEmpty(end)){
									ageList.add(tempMap); //无具体规则
								}else{
									if(!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)){//开始和结束都传入
										if(ToolUtils.isNumeric(start) && ToolUtils.isNumeric(end)){
											if(age>=Integer.parseInt(start) && age<=Integer.parseInt(end)){
												ageList.add(tempMap);
											}
										}else{
											ageList.add(tempMap); //无具体规则
										}
									}else if(!StringUtils.isEmpty(start)){ //只传入开始时间
										if(ToolUtils.isNumeric(start)){
											if(age>=Integer.parseInt(start)){
												ageList.add(tempMap);
											}
										}else{
											ageList.add(tempMap); //无具体规则
										}
									}else if(!StringUtils.isEmpty(end)){//只传入结束时间
										if(ToolUtils.isNumeric(end)){
											if(age<=Integer.parseInt(end)){
												ageList.add(tempMap);
											}
										}else{
											ageList.add(tempMap); //无具体规则
										}
									}
								}

							}else{
								ageList.add(tempMap); //无具体规则
							}
						}else{ //没有规则限制 默认可以推送
							ageList.add(tempMap);
						}
					}else if(Constants.EDUCATION_PUSH_TYPE_REGISTER.equals(tempMap.get("type"))){
						pushRules = (null == tempMap.get("pushRule")) ? null : String.valueOf(tempMap.get("pushRule"));
						if(null != pushRules){
							if(pushRules.split("-",2).length == 2){
								String start = pushRules.split("-",2)[0];
								String end = pushRules.split("-",2)[1];
								if(StringUtils.isEmpty(start) && StringUtils.isEmpty(end)){
									gisterTimeList.add(tempMap); //无具体规则
								}else{
									if(!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)){//开始和结束都传入
										if(ToolUtils.isNumeric(start) && ToolUtils.isNumeric(end)){
											if(day>=Integer.parseInt(start) && day<=Integer.parseInt(end)){
												gisterTimeList.add(tempMap);
											}
										}else{
											gisterTimeList.add(tempMap); //无具体规则
										}
									}else if(!StringUtils.isEmpty(start)){ //只传入开始时间
										if(ToolUtils.isNumeric(start)){
											if(day>=Integer.parseInt(start)){
												gisterTimeList.add(tempMap);
											}
										}else{
											gisterTimeList.add(tempMap); //无具体规则
										}
									}else if(!StringUtils.isEmpty(end)){//只传入结束时间
										if(ToolUtils.isNumeric(end)){
											if(day<=Integer.parseInt(end)){
												gisterTimeList.add(tempMap);
											}
										}else{
											gisterTimeList.add(tempMap); //无具体规则
										}
									}
								}

							}else{
								gisterTimeList.add(tempMap); //无具体规则
							}
						}else{ //没有规则限制 默认可以推送
							gisterTimeList.add(tempMap);
						}
					}else if(Constants.EDUCATION_PUSH_TYPE_RAND.equals(tempMap.get("type"))){
						randomList.add(tempMap);
					}
				}
			}

			//先查询全局推送  按权重取前6条
			if(globalList.size() >= count){
				list.addAll(globalList.subList(0,count));
				logger.info("in getContentlistforApp 全局推送:"+list.size());
				return list;
			}else{
				list.addAll(globalList);
			}

			int remaining = count - list.size(); //还需要取几条

			//纠正年龄推送
			if(correctAgeList.size() >= remaining ){
				list.addAll(correctAgeList.subList(0,remaining));
				logger.info("in getContentlistforApp 纠正年龄:"+list.size());
				return list;
			}else{
				list.addAll(correctAgeList);
			}

			remaining -= correctAgeList.size();
			//实际年龄推送
			if(ageList.size() >= remaining ){
				list.addAll(ageList.subList(0,remaining));
				logger.info("in getContentlistforApp 胎龄推送:"+list.size());
				return list;
			}else{
				list.addAll(ageList);
			}

			remaining -= ageList.size();
			//建档时间推送
			if(gisterTimeList.size() >= remaining ){
				list.addAll(gisterTimeList.subList(0,remaining));
				logger.info("in getContentlistforApp 建档时间推送:"+list.size());
				return list;
			}else{
				list.addAll(gisterTimeList);
			}

			//随机推送
			remaining -= gisterTimeList.size();
			if(randomList.size() >= remaining ){
				list.addAll(randomList.subList(0,remaining));
				logger.info("in getContentlistforApp 随机推送:"+list.size());
				return list;
			}else{
				list.addAll(randomList);
			}
		}else{
			//如果没有查到用户信息  则随机取六条返回
			logger.info("out getContentlistforApp");
			if(educationList.size() > count ){
				list.addAll(educationList.subList(0,count));
				logger.info("in 没有传用户信息 随机取六条:"+list.size());
				return list;
			}else{
				list.addAll(educationList);
			}

			return list;
		}


        logger.info("out getContentlistforApp");
		return list;
	}


}
